package com.bwf.pool;

import java.util.concurrent.*;

/**
 * @Version v1.0
 * @Description: TODO
 * @Author ZHANZHONGXIN
 * @Date 2022/5/20 15:43
 * @Copyright 博为峰
 */
public class ExecutorDemo {
    public static void main(String[] args) {
        //1.创建带缓存的线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程池");
            }
        });
        //2.创建固定线程数的线程池
        Executors.newFixedThreadPool(10);
        //3.创建单个线程的线程池
        Executors.newSingleThreadExecutor();
        //4.创建定时执行的线程池
        Executors.newScheduledThreadPool(10);

//        ThreadPoolExecutor(int corePoolSize,                   //核心线程数
//                            int maximumPoolSize,               //最大线程数
//                            long keepAliveTime,                //存活时间
//                            TimeUnit unit,                     //时间单位
//                            BlockingQueue<Runnable> workQueue, //缓存队列
//                            RejectedExecutionHandler handler)       //拒绝策略
        /*
           拒绝策略：AbortPolicy丢弃任务，抛出异常（默认）
                   CallerRunsPolicy，由调用（提交任务的线程）线程处理
                   DiscardOldestPolicy，丢弃队列最前面的任务
                   DiscardPolicy，丢弃任务，不抛出异常

                   10 + 5 + 5 = 20
                   最大线程数15+缓存队列5=20

         */
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(10,
                15,
                100,
                TimeUnit.MINUTES,
                new ArrayBlockingQueue<>(5));
        for (int i = 0; i < 25; i++) {//提交给线程池的任务数
            poolExecutor.submit(new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j < 10; j++) {
                        System.out.println(Thread.currentThread().getName() + "," + j);
                    }
                }
            });
        }

    }
}
